import router from "./router";
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import store from "./store";
import { asyncRoutes } from "@/router"
// 前置守卫
const whileList = ['/login', '/404']
router.beforeEach(async (to, from, next) => {
  nprogress.start()     //进度条
  if (store.getters.token) {   //存在token的情况
    if (to.path === '/login') {
      next('/')  // 跳转到主页
      nprogress.done()
    } else {
      // 判断是否获取过数据
      if (!store.getters.userId) {
        const { roles } = await store.dispatch('user/getUserInfo')  // 再次派发actions
        // console.log(roles.menus);
        // console.log(asyncRoutes);
        const filterRoutes = asyncRoutes.filter((item) => {
          return roles.menus.includes(item.name)
        })
        store.commit('user/setRoutes', filterRoutes)
        // console.log(filterRoutes);
        // 添加动态路由信息到路由
        // router添加动态路由信息后需要转发一下
        router.addRoutes([...filterRoutes, { path: '*', redirect: '/404', hidden: true }])
        next(to.path)
      } else {
        next()   //放过
      }
    }
  } else {  //去白名单的地址
    if (whileList.includes(to.path)) {
      next()
    } else {         //不存在token的情况
      next('login')  //中转到登录界面
      nprogress.done()
    }
  }
})

// 后置守卫
router.afterEach(() => {
  nprogress.done()
})

